package services

import beans.Order
import com.jfinal.plugin.activerecord.Db
import base.Message
import base.State
import common.permission.Permission
import common.permission.PermissionManager
import controllers.OrderController
import models.BoughtM
import models.OrderM
import models.RecordM
import java.sql.Timestamp

class OrderService(controller: OrderController):
        BaseService<OrderController>(controller) {

    fun createNewOrder(userId: Int, recordId: Int, toAddr: String){
        //权限检测
        if (!PermissionManager.checkUserPermission(userId, Permission.BUY)){
            val message = Message(State.STATE_FAIL, data = State.getEorrorStr(State.ERROR_ORDER_NO_BUY_PERMISSION))
            controller.renderJson(message)
            return
        }
        val recordM = RecordM.AGENT.findById(recordId)
        if (recordM.getInt(RecordM.STATE) != RecordState.PASS){
            val message = Message(State.STATE_FAIL, data = State.getEorrorStr(State.ERROR_ORDER_GOODS_NOT_EXIST))
            controller.renderJson(message)
            return
        }
        val orderM = OrderM()
        orderM.set(OrderM.USER_ID, userId)
        orderM.set(OrderM.RECORD_ID, recordId)
        orderM.set(OrderM.TO_ADDR, toAddr)
        orderM.set(OrderM.CREATE_TIME, Timestamp(System.currentTimeMillis()))
        orderM.set(OrderM.STATE, OrderState.PROCESSING)
        recordM[RecordM.STATE] = RecordState.SOLD
        val isSuccess = Db.tx{
            return@tx recordM.update() && orderM.save()
        }
        if (isSuccess){
            val message = Message(State.STATE_SUCCESS, data = Order.fromModel(orderM, null))
            controller.renderJson(message)
        } else {
            val message = Message(State.STATE_FAIL, data = State.getEorrorStr(State.ERROR_ORDER_UNKNOWN))
            controller.renderJson(message)
        }
    }

    fun finishOrder(userId: Int, roderdId: Int){
        val model = OrderM.findOrderByIdWithUserId(roderdId, userId)
        if (model == null){
            val message = Message(State.STATE_FAIL, data = State.getEorrorStr(State.ERROR_ORDER_NOT_EXIST))
            controller.renderJson(message)
            return
        }
        model[OrderM.STATE] = OrderState.FINISH
        model[OrderM.FINISH_TIME] = Timestamp(System.currentTimeMillis())
        val recordId = model.getInt(OrderM.RECORD_ID)

        val boughtM = BoughtM()
        boughtM.set(BoughtM.RECORD_ID, recordId)
        boughtM.set(BoughtM.USER_ID, userId)
        val isSuccess = Db.tx{
            return@tx model.update() && boughtM.save()
        }
        if (isSuccess){
            val message = Message(State.STATE_SUCCESS, data = "")
            controller.renderJson(message)
        } else {
            val message = Message(State.STATE_FAIL, data = State.getEorrorStr(State.ERROR_ORDER_UNKNOWN))
            controller.renderJson(message)
        }
    }

    fun cancelOrder(userId: Int, roderdId: Int){
        val model = OrderM.findOrderByIdWithUserId(roderdId, userId)
        if (model == null){
            val message = Message(State.STATE_FAIL, data = State.getEorrorStr(State.ERROR_ORDER_NOT_EXIST))
            controller.renderJson(message)
            return
        }
        model[OrderM.STATE] = OrderState.CANCEL
        model[OrderM.FINISH_TIME] = Timestamp(System.currentTimeMillis())
        if (model.update()){
            val message = Message(State.STATE_SUCCESS, data = "")
            controller.renderJson(message)
        } else {
            val message = Message(State.STATE_FAIL, data = State.getEorrorStr(State.ERROR_ORDER_UNKNOWN))
            controller.renderJson(message)
        }
    }

    fun payOrder(userId: Int, roderId: Int){
        val model = OrderM.findOrderByIdWithUserId(roderId, userId)
        if (model == null){
            val message = Message(State.STATE_FAIL, data = State.getEorrorStr(State.ERROR_ORDER_NOT_EXIST))
            controller.renderJson(message)
            return
        }
        model[OrderM.PAY_TIME] = Timestamp(System.currentTimeMillis())
        val recordId = model.getInt(OrderM.RECORD_ID)
        val recordM = RecordM.AGENT.findById(recordId)
        recordM[RecordM.STATE] = RecordState.SOLD
        val isSuccess = Db.tx {
            return@tx model.update() && recordM.update()
        }
        if (isSuccess){
            val message = Message(State.STATE_SUCCESS, data = "")
            controller.renderJson(message)
        } else {
            val message = Message(State.STATE_FAIL, data = State.getEorrorStr(State.ERROR_ORDER_UNKNOWN))
            controller.renderJson(message)
        }
    }

    fun listAllOrders(userId: Int) {
        val list = OrderM.findOrderByUserId(userId)
        if (list.isEmpty()){
            val message = Message(State.STATE_FAIL, data = State.getEorrorStr(State.ERROR_ORDER_NOT_ORDERS))
            controller.renderJson(message)
        } else {
            val orders = mutableListOf<Order>()
            list.forEach {
                val recordId = it.getInt(OrderM.RECORD_ID)
                val recordM = RecordM.AGENT.findById(recordId)
                val order = Order.fromModel(it, recordM)
                orders.add(order)
            }
            val message = Message(State.STATE_SUCCESS, data = orders)
            controller.renderJson(message)
        }
    }

}

object OrderState{
    const val PROCESSING = 0
    const val FINISH = 1
    const val CANCEL = 2
}